<script setup lang="ts">
import type { Page } from '@/types'
import { getFormatDictMap } from '@/util/dict'
import { onMounted, ref } from 'vue'
import { Search, Refresh } from '@/util/icons'
import Pagination from '@/components/Pagination.vue'
import type { RoleTable } from '@/types/role'
import { getAllRole } from '../role/api'
import type { UserTable } from '@/types/user'
import { getUserRoles, updateUserRoles } from '@/api/user'
import { ElMessage } from 'element-plus'
const props = defineProps<{
  dMap: Map<string, string>
  editData: UserTable
  // 刷新
  refresh: () => void
}>()
// 关闭
const emit = defineEmits<{
  (event: 'cDlg'): void
}>()

const page = ref<Page<RoleTable>>({
  num: 1,
  size: 10,
  rows: [],
  count: 0
})
/* 获取对应的字典信息 */
const tableDict = ref<Map<string, string>>()
const statusDict = ref<Map<string, string>>()

// 页面加载
const loading = ref<boolean>(false)
// 获取页面数据
function getPageData() {
  loading.value = true
  getAllRole(page.value, searchForm.value)
    .then((tabs) => {
      page.value = tabs.data
    })
    .finally(() => {
      setTimeout(() => {
        loading.value = false
      }, 500)
    })
}

// 用户角色权限
const userRoles = ref<number[]>([])
function getUserRoleData() {
  getUserRoles(props.editData.uId!).then((d) => {
    userRoles.value = d.data.map<number>((d) => {
      return d.rId!
    })
  })
}
/**
 *
 * @param rid 更改用户角色的权限
 */
function changeUserRole(rid: number) {
  const index = userRoles.value.indexOf(rid)
  if (index >= 0) {
    userRoles.value.splice(index, 1)
  } else {
    userRoles.value.push(rid)
  }
}
onMounted(() => {
  getFormatDictMap('sys_role_manage', 'head').then((d) => {
    tableDict.value = d
  })
  getFormatDictMap('sys_role_status', 'val').then((d) => {
    statusDict.value = d
  })
  getPageData()
  getUserRoleData()
})

/* 搜索 */
/* 是否展示搜索栏 */
const showSearchBar = ref<boolean>(false)
const searchForm = ref<RoleTable>({
  name: '',
  key: ''
})

// 重置搜索框
function reSearch() {
  searchForm.value = {
    name: '',
    key: '',
    status: ''
  }
  getPageData()
}
/* 选择器 */
const selectData = ref<RoleTable[]>([])
function onSelect(data: RoleTable[]) {
  selectData.value = data
}

function cancel() {
  emit('cDlg')
}

function edit() {
  updateUserRoles(props.editData.uId!, userRoles.value)
    .then((d) => {
      ElMessage.success(d.msg)
      emit('cDlg')
    })
    .catch((d) => {
      ElMessage.error(d.msg)
    })
}
</script>

<template>
  <div class="control">
    <div class="search" v-show="showSearchBar">
      <el-form :inline="true">
        <el-form-item :label="tableDict?.get('name') || 'name'">
          <el-input
            v-model="searchForm.name"
            :placeholder="'请输入' + tableDict?.get('name') || 'name'"
          ></el-input>
        </el-form-item>
        <el-form-item :label="tableDict?.get('key') || 'key'">
          <el-input
            v-model="searchForm.key"
            :placeholder="'请输入' + tableDict?.get('key') || 'key'"
          ></el-input>
        </el-form-item>
        <el-form-item :label="tableDict?.get('status') || 'status'">
          <el-select
            v-model="searchForm.status"
            :placeholder="'请选择' + tableDict?.get('status') || 'status'"
          >
            <el-option label="无" value="" />
            <el-option :label="statusDict?.get('1') || '1'" value="1" />
            <el-option :label="statusDict?.get('0') || '0'" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getPageData">搜索</el-button>
          <el-button :icon="Refresh" @click="reSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="ctl-bts">
      <span class="ctl-r">
        <el-button :icon="Search" circle @click="showSearchBar = !showSearchBar"></el-button>
        <el-button :icon="Refresh" @click="getPageData" circle></el-button>
      </span>
    </div>
  </div>
  <div class="ctx">
    <el-table
      v-loading="loading"
      table-layout="auto"
      :stripe="true"
      :data="page.rows"
      height="100%"
      :flexible="true"
      @selection-change="onSelect"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="name" align="center">
        <template #header>
          {{ tableDict?.get('name') || 'name' }}
        </template>
      </el-table-column>
      <el-table-column prop="key" align="center">
        <template #header>
          {{ tableDict?.get('key') || 'key' }}
        </template>
        <template #default="{ row }">
          <span class="highlight-info">{{ row['key'] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" align="center">
        <template #header>
          {{ tableDict?.get('status') || 'status' }}
        </template>
        <template #default="{ row }">
          <el-tag :type="row['status'] === '1' ? 'success' : 'danger'">{{
            statusDict?.get(row['status']) || row['status']
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center">
        <template #header>授权</template>
        <template #default="{ row }">
          <el-switch
            :modelValue="userRoles.includes(row['rId'])"
            @change="changeUserRole(row['rId'])"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          ></el-switch>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <Pagination :page="page" :get-page-data="getPageData" />
  <div class="buttons">
    <el-button type="primary" @click="cancel">取消</el-button>
    <el-button type="success" @click="edit">保存</el-button>
  </div>
</template>
<style scoped lang="less">
@import '../../../assets/page_bgl.less';

.buttons {
  display: flex;
  margin-top: 30px;
  justify-content: flex-end;
}

.ctx {
  height: 40vh;
}
</style>
